package qc.module.ehs.api.controller;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import qc.common.core.exception.QCPromptException;
import qc.module.ehs.dto.org.EhsOrgDto;
import qc.module.ehs.service.EhsOrgService;
import qc.module.platform.dto.dept.DeptSimpleDto;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * EhsOrgController
 *
 * @author QuCheng Tech
 * @create 2024/5/22
 */
@RestController
@RequestMapping("/org")
public class OrgController {
    
    @Autowired
    private EhsOrgService service;

    @Autowired
    HttpServletRequest request;
    
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;
    

    /**
     * 获取所有
     * 
     * @return List<EhsOrgDto> 组织信息DTO集合
     * @author QuCheng Tech
     * @since 2024/5/22
     */
    @GetMapping("/all")
    private List<EhsOrgDto> getAll(){
        return service.getAll();
    }

    /**
     * 获取指定 -支持@RequestParam与@PathVariable两种方式
     * 
     * @param id 组织代码
     * @return EhsOrgDto 组织信息DTO
     * @author QuCheng Tech
     * @since 2024/5/22
     */
    @GetMapping("/get")
    public EhsOrgDto getByParam(@RequestParam String id) throws QCPromptException {
        return service.get(id);
    }

    /**
     * 获取指定 -支持@RequestParam与@PathVariable两种方式
     *
     * @param id 组织代码
     * @return EhsOrgDto 组织信息DTO
     * @author QuCheng Tech
     * @since 2024/5/22
     */
    @GetMapping("/get/{id}")
    public EhsOrgDto getByPath(@PathVariable String id) throws QCPromptException {
        return service.get(id);
    }

    /**
     * 新增
     *
     * @param dto 组织信息
     * @return 成功返回null，失败返回错误或提示信息
     * @author QuCheng Tech
     * @since 2024/5/22
     */
    @RequestMapping(value = "/add",method = {RequestMethod.GET,RequestMethod.POST})
    public String add(@RequestBody EhsOrgDto dto){
        return service.add(dto);
    }

    /**
     * 修改
     *
     * @param dto 组织信息
     * @return 成功返回null，失败返回错误或提示信息
     * @author QuCheng Tech
     * @since 2024/5/22
     */
    @RequestMapping(value = "/update",method = {RequestMethod.POST,RequestMethod.PUT})
    public String update(@RequestBody EhsOrgDto dto){
        return service.update(dto);
    }

    /**
     * 删除 -支持@RequestParam与@PathVariable两种方式
     *
     * @param id 组织代码
     * @return 成功返回null，失败返回错误或提示信息
     * @author QuCheng Tech
     * @since 2024/5/22
     */
    @DeleteMapping("/delete")
    public String deleteByParam(@RequestParam String id){
        return service.delete(id);
    }

    /**
     * 删除 -支持@RequestParam与@PathVariable两种方式
     *
     * @param id 组织代码
     * @return 成功返回null，失败返回错误或提示信息
     * @author QuCheng Tech
     * @since 2024/5/22
     */
    @DeleteMapping("/delete/{id}")
    public String deleteByPath(@PathVariable String id){
        return service.delete(id);
    }

    /**
     * 根据项目编码获取用户所属组织信息，同时支持@RequestParam和@PathVariable方式
     * 
     * @param projectcode 项目编码
     * @return EhsOrgDto
     * @throws QCPromptException
     * @author QuCheng Tech
     * @since 2024/6/11
     */
    @GetMapping("/getorg")
    public EhsOrgDto getUserOrgByParam(@RequestParam String projectcode) throws QCPromptException {
        if (StringUtils.isBlank(projectcode)) throw new QCPromptException("项目编码不能为空");
        //根据项目编码查询当前用户所属的根部门
        List<DeptSimpleDto> rootDepts = getProjectValidRootDepts(projectcode);
        List<Integer> rootDeptIds = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(rootDepts)){
            rootDeptIds = rootDepts.stream().map(DeptSimpleDto::getId).collect(Collectors.toList());
        }
        return service.getUserOrg(rootDeptIds);
    }

    /**
     * 根据项目编码获取用户所属组织信息，同时支持@RequestParam和@PathVariable方式
     *
     * @param projectcode 项目编码
     * @return EhsOrgDto
     * @throws QCPromptException
     * @author QuCheng Tech
     * @since 2024/6/11
     */
    @GetMapping("/getorg/{projectcode}")
    public EhsOrgDto getUserOrgByPath(@PathVariable String projectcode) throws QCPromptException {
        if (StringUtils.isBlank(projectcode)) throw new QCPromptException("项目编码不能为空");
        //根据项目编码查询当前用户所属的根部门
        List<DeptSimpleDto> rootDepts = getProjectValidRootDepts(projectcode);
        List<Integer> rootDeptIds = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(rootDepts)){
            rootDeptIds = rootDepts.stream().map(DeptSimpleDto::getId).collect(Collectors.toList());
        }
        return service.getUserOrg(rootDeptIds);
    }

    /**
     * 根据项目编码获取用户所在项目中有效的根部门集合
     *
     * @param projectCode 项目编码
     * @return 部门简要信息集合
     * @author QuCheng Tech
     * @since 2024/5/23
     */
    public List<DeptSimpleDto> getProjectValidRootDepts(String projectCode) {
        Map<String,String> params = new HashMap<>();
        params.put("id",projectCode);
        
        ServiceInstance service = discoveryClient.getInstances("module-platform").get(0);
        String url = "http://" + service.getHost() + ":" + service.getPort() + "/dept/projectvalidrootdept/{id}";

        HttpEntity<String> formEntity = new HttpEntity<String>(projectCode, null);
        ParameterizedTypeReference<List<DeptSimpleDto>> responseType = new ParameterizedTypeReference<List<DeptSimpleDto>>() {
        };

        ResponseEntity<List<DeptSimpleDto>> response = restTemplate.exchange(
                url,//获取资源的地址
                HttpMethod.GET,
                formEntity,
                responseType,
                params
        );
        List<DeptSimpleDto> resultDto = response.getBody();
        return resultDto;
    }
}
